import React from 'react';
import {connect} from 'react-redux';
import {Button, Row, Col, Input, Checkbox, Modal, Icon, Alert, Progress, message} from 'antd';
import SSService from 'containers/setting/security-setting/security-setting.service';
import {messages} from "share/common";
import 'styles/setting/security-setting/clear-modal.scss';
import TryloginService from "../../login/components/try-login/try-login.service";
import LoginService from "../../login/login.service";
import VoiceCode from 'containers/login/components/voice-code/voice-code';
import ExportService from 'components/template/export-modal/export-modal.service';

class ClearModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      //欢迎消息模态框
      carousels: [],
      checkVisible: false,
      clearVisible: false,
      progressVisible: false,
      checked: false,
      codeTime: 0,//验证码倒数的时间
      copyInterval: null,
      src: "",//验证码图片路径
      attachmentOID: "",//验证码图片路径
      picCode: null,//图形验证码
      loading: false,//button
      clearLoading: false,//button
      phoneCode: "",
      progressNum: 0,
      timer: null,
      clearError: false,
      errorMsg: null,
    };
  }

  componentWillMount() {
  }


  setClearVisible = (flag) => {
    this.setState({
      clearVisible: flag,
    });
  };

  setCheckVisible = () => {
    clearInterval(this.state.copyInterval);
    this.setState({
      checkVisible: false,
      checked: false,
      codeTime: 0
    });
  };
  setCheckVisibleTrue = () => {
    this.setState({
      checkVisible: true,
    });
  };

  setProgressVisible= (flag) => {
    this.setState({
      progressVisible: flag,
    });
    clearTimeout(this.state.timer);
  };

  onCheckedChange = (e) => {
    this.setState({
      checked: e.target.checked,
    })
  };

  handleOk = () => {
    this.setClearVisible(false);
    this.setCheckVisibleTrue(true);
    this.getVerifyCodeImage();
  };

  //输入验证码时
  onPicCodeChange = (e) => {
    this.setState({
      picCode: e.target.value,
      loading: false,
    });
  };

  //获取验证码图片
  getVerifyCodeImage = () => {
    this.setState({
      imgLoading: true,
    });
    TryloginService.getVerifyCodeImage()
      .then(res => {
        let src = "data:image/png;base64," + res.data.image;
        this.setState({
          src: src,
          attachmentOID: res.data.attachmentOID,
          imgLoading: false,
        });
      }).catch(err => {
      this.setState({
        imgLoading: false,
      });
    })
  };

  //获取验证码
  getConfirmCode = (e, sendVoiceCode) => {
    const {attachmentOID, picCode} = this.state;
    const {user} = this.props;
    let publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCyjnL+41/pse3E0a6bM68zNnsYj2C1wEH76WY0qpIGkTWWl6DynhcV0v5S+Z4Mxj211CPBx43bcdTZoFW//sut1W68VJrJobFJxkV2mJuzreKUxqjL7FjdbAfZR5y7OAg7ueYlX5tRTIcbtb56c6KpCIz7cuEU853tgoTxUBVr1wIDAQAB";
    let params = {
      mobile: LoginService.encrypt(user.mobile, publicKey),
      verifyCode: picCode,
      attachmentOID: attachmentOID,
      cryptType: 3,
      isRegisterVerify: false,
    };
    if (sendVoiceCode) {
      params.messageType = 'voice';
    } else {
      this.setState({
        loading: true,
      });
    }
    TryloginService.sendPhoneToken(params).then(
        res => {
          if (sendVoiceCode) {
            message.success(messages('basic-14.key130')/*语音验证码已发送，请注意接听*/);
          } else {
            this.setState({
              loading: false,
              codeTime: 60,
            }, () => {
              message.success(messages('common-1.key240')/*发送成功*/)
              let copyInterval = setInterval(() => {
                let codeTime = this.state.codeTime;
                if (codeTime > 0) {
                  codeTime--;
                  this.setState({
                    codeTime,
                    copyInterval,
                  });
                }
                if (codeTime <= 0) {
                  this.voiceCodeRef && this.voiceCodeRef.reset();
                  clearInterval(copyInterval)
                }
              }, 1000);
            });
          }
        }
      ).catch(res => {
        this.getVerifyCodeImage();
        this.setState({
          loading: false,
        })
      });
  };


  //输入验证码时
  enterConfirmCodeChange = (e) => {
    this.setState({
      phoneCode: e.target.value,
    });
  };

  clearData = () => {
    this.setState({
      clearLoading: true,
    });
    const {phoneCode, copyInterval} = this.state;
    SSService.clearData(phoneCode).then(res => {
      clearInterval(copyInterval);
      this.setState({
        checkVisible: false,
        progressVisible: true,
        codeTime: 0
      });
      this.getProgress(res.data);
      this.setState({
        clearLoading: false,
      })
    }).catch(res => {
      this.setState({
        clearLoading: false,
      })
    })
  };

  getProgress = (transactionOid) => {
    const {progressVisible} = this.state;
    SSService.getProgress(transactionOid)
      .then(res => {
        if(res.data.errorCode === "0000"){
          if(res.data.progress !== 100 && progressVisible){
            clearTimeout(this.state.timer);
            let timer = setTimeout(() => {
              this.getProgress(transactionOid);
              this.setState({
                timer,
                progressNum: res.data.progress,
              });
            }, 2000)
          }else{
            this.setState({
              progressNum: res.data.progress,
            });
            clearTimeout(this.state.timer);
          }
        }else{
          this.setState({
            clearError: true,
            errorMsg: res.data.errorMsg,
          });
          // message.error(res.data.errorMsg);
          clearTimeout(this.state.timer);
        }
      }).catch(res => {
      clearTimeout(this.state.timer);
      message.error(messages('basic-14.key1')/*系统异常*/);
    })
  };

  render() {
    const {checked, src, codeTime, checkVisible, clearLoading, clearVisible,
      imgLoading, picCode, phoneCode, progressVisible, progressNum, clearError, errorMsg} = this.state;
    let {user, menuTree, tenantMode, voiceCodeEnable} = this.props;
    let role = menuTree.allAPIMenuItem["person-manage"];
    let footer = (
      <div>
        <Button onClick={() => this.setClearVisible(false)}>{messages('common.cancel')/*取消*/}</Button>
        <Button onClick={this.handleOk} disabled={!checked} type="primary">{messages('common.ok')/*确定*/}</Button>
      </div>
    );
    let checkFooter = (
      <div>
        <Button onClick={this.setCheckVisible}>{messages('common.cancel')/*取消*/}</Button>
        <Button onClick={this.clearData}
                disabled={!user.mobile || !picCode || !phoneCode}
                loading={clearLoading}
                type="danger">
          {messages('common.clear')/*清空*/}
        </Button>
      </div>
    );
    let progressFooter = (
      <Button onClick={() => this.setProgressVisible(false)} type="primary">{messages('basic-14.key2')/*关闭*/}</Button>
    );
    let extraMessage = messages('basic-14.key131',{arg1: role.url,arg2: role?role.resourceName:messages('menu.person-manage')})/*请先至&nbsp;<a href={arg1} target='_blank'>{arg2}</a>&nbsp;维护手机号，再进行清空操作*/;
    return (
      <div className="clear-data-modal">
        <Button onClick={()=>this.setClearVisible(true)} disabled={!tenantMode}>
          <Icon type="delete"/> {messages('basic-14.key3')/*清空业务数据*/}
        </Button>
        <div className="clear-data-modal-wrap"/>
        <div className="clear-data-modal-wrap-second"/>
        <Modal visible={clearVisible}
               title={messages('basic-14.key3')/*清空业务数据*/}
               footer={footer}
               width={620}
               onCancel={() => this.setClearVisible(false)}
               getContainer={() => document.getElementsByClassName('clear-data-modal-wrap')[0]}>
          <div className="margin-bottom-gap">{messages('basic-14.key4')/*注意事项： 此操作将会清空企业所有员工的单据数据，包含以下：*/}</div>
          <div className="margin-bottom-gap note-detail-wrap">
            <div className="margin-bottom-gap note-detail-title">{messages('basic-14.key5')/*- 所有单据、费用和发票等相关数据*/}</div>
            <div className="margin-bottom-gap note-detail-title">{messages('basic-14.key6')/*- 所有审批历史*/}</div>
            <div className="margin-bottom-gap note-detail-title">{messages('basic-14.key7')/*- 所有报表统计数据*/}</div>
            <div className="margin-bottom-gap note-detail-title">{messages('basic-14.key8')/*- 所有预算执行数据*/}</div>
            <div className="margin-bottom-gap note-detail-title">{messages('basic-14.key9')/*- 所有被清理数据相关的报表数据*/}</div>
            <div className="margin-bottom-gap">
              <Checkbox checked={checked} onChange={this.onCheckedChange}>
                <span>{messages('basic-14.key10')/*此操作无法撤销或恢复，我已了解并愿意承担此操作的风险*/}</span>
              </Checkbox>
            </div>
          </div>
        </Modal>
        <Modal title={messages('basic-14.key11')/*清空数据校验*/}
               width={620}
               visible={checkVisible}
               footer={checkFooter}
               onCancel={this.setCheckVisible}
               getContainer={() => document.getElementsByClassName('clear-data-modal-wrap-second')[0]}>
          <Alert message={messages('basic-14.key12')/*为了确认您本人操作，请完成以下验证*/} type="info" showIcon style={{marginBottom: 25}}/>
          <div className="data-check-item">
            <div className="data-check-title"><span style={{color: 'red'}}>*&nbsp;</span>{messages('basic-14.key13')/*手机号*/}</div>
            <div className="data-check-input">
              <Input disabled={true}
                     value={user.mobile ? user.mobile.substring(0,3) + "****" + user.mobile.substring(7,11) : ""}
                     placeholder={user.mobile ? messages('basic-14.key14')/*请输入temp2*/ : messages('basic-14.key15')/*尚未维护*/}/>
              <div>
                {
                  !user.mobile &&
                  <div dangerouslySetInnerHTML={{__html: extraMessage}} />
                }
              </div>
            </div>
            <div className="clear"/>
          </div>
          <div className="data-check-item">
            <div className="data-check-title"><span style={{color: 'red'}}>*&nbsp;</span>{messages('basic-14.key17')/*图片验证码*/}</div>
              <div className="verify-code data-check-input">
                <Input disabled={!user.mobile}
                       className="verify-code-inp"
                       placeholder={messages('helios.login.input.verify.code')/*请输入图片验证码*/}
                       onChange={this.onPicCodeChange}/>
                <div className="verify-code-img">
                  {
                    src ? <img src={src} onClick={this.getVerifyCodeImage} className="pic-code-img"/>
                      : <span onClick={this.getVerifyCodeImage} className="pic-code-text">
                        {imgLoading ? messages('basic-14.key18')/*加载中...*/ :
                          messages('basic-14.key19')/*加载失败*/}
                      </span>
                  }
                </div>
              </div>
            <div className="clear"/>
          </div>
          <div className="data-check-item">
            <div className="data-check-title"><span style={{color: 'red'}}>*&nbsp;</span>{messages('basic-14.key20')/*验证码*/}</div>
            <div className="verify-code2 data-check-input">
              <Input disabled={!user.mobile}
                     className="verify-code-inp"
                     placeholder={messages('basic-14.key21')/*请输入短信验证码*/}
                     onChange={this.enterConfirmCodeChange}/>
              <div className="verify-code-link">
                {
                  codeTime === 0 ?
                    <a onClick={this.getConfirmCode}>{messages('basic-14.key22')/*获取短信验证码*/}</a>
                    : <span className="clock-time">
                      {codeTime}&nbsp;s
                      {voiceCodeEnable && <VoiceCode sendVoiceCode={(e)=>{this.getConfirmCode(e, true)}} onRef={ref => this.voiceCodeRef = ref} />}
                    </span>
                }
              </div>
            </div>
            <div className="clear"/>
          </div>
        </Modal>
        <Modal title={messages('basic-14.key23')/*清空数据*/}
               width={620}
               visible={progressVisible}
               footer={progressFooter}
               onCancel={() =>this.setProgressVisible(false)}>
          <Progress percent={progressNum} status={clearError ? "exception" : "active"}/>
          {errorMsg}
        </Modal>
      </div>

    );
  }
}

ClearModal.contextTypes = {
  router: React.PropTypes.object
};
function mapStateToProps(state) {
  return {
    user: state.login.user,
    menuTree: state.login.menuTree,
    tenantMode: state.main.tenantMode,
    voiceCodeEnable: state.login.voiceCodeEnable,
  }
}

export default connect(mapStateToProps)(ClearModal);



